//
//  ApplyPersonInfoViewController.swift
//  LongTermInsurance
//
//  Created by zolobdz on 2018/11/28.
//  Copyright © 2018年 HeChao. All rights reserved.
//

import UIKit
import ObjectMapper
import RxCocoa
import RxSwift

class ApplyPersonInfoViewController: BaseTableViewController {

    lazy var dataSourceFirst = [ApplyPersonInfo]()
    lazy var dataSourceSecond = [ApplyPersonInfo]()
    
    let info = MyselfSingleton.shared.userInfo!
    
    // setion 0
    
    let nameApply = ApplyPersonInfo(titleName: "姓 名", type: .base, placeholder: "", detailText: "")
    let sexApply = ApplyPersonInfo(titleName: "性 别", type: .base, placeholder: "", detailText: "")
    let birthApply = ApplyPersonInfo(titleName: "出生年月", type: .base, placeholder: "", detailText: "")
    let idApply = ApplyPersonInfo(titleName: "省份证号码", type: .base, placeholder: "", detailText: "")
    let shebaoIDApply = ApplyPersonInfo(titleName: "社保个人编号", type: .base, placeholder: "", detailText: "")
    
    let marriedApply = ApplyPersonInfo(titleName: "婚姻状况", type: .choose, placeholder: "", detailText: "", chooseType: "7")
    let homeTownApply = ApplyPersonInfo(titleName: "户籍地址", type: .enter, placeholder: "请输入您的户籍地址", detailText: "")
    let liveAddress = ApplyPersonInfo(titleName: "居住地址(上门评估地址)", type: .enter, placeholder: "请输入您的居住地址", detailText: "")
    let teleApply = ApplyPersonInfo(titleName: "住宅电话", type: .enter, placeholder: "请输入您的住宅电话(可选)", detailText: "")
    let mobileApply = ApplyPersonInfo(titleName: "移动电话", type: .enter, placeholder: "请输入您的手机号码", detailText: "")
    
    // setion 1
    
    let helpNameApply = ApplyPersonInfo(titleName: "监护人姓名", type: .enter, placeholder: "请输入监护人姓名", detailText: "")
    let helpTeleApply = ApplyPersonInfo(titleName: "监护人住宅电话", type: .enter, placeholder: "请输入监护人住宅电话(可选)", detailText: "")
    let helpMobile = ApplyPersonInfo(titleName: "监护人移动电话", type: .enter, placeholder: "请输入监护人手机号码", detailText: "")
    let helpRelationApply = ApplyPersonInfo(titleName: "与参保人的关系", type: .choose, placeholder: "", detailText: "", chooseType: "8")
    let helpSMSApply = ApplyPersonInfo(titleName: "短信通知手机号", type: .enter, placeholder: "请输入短信通知手机号", detailText: "")
    let helpMailReceiverApply = ApplyPersonInfo(titleName: "邮寄收件人", type: .enter, placeholder: "邮寄收件人", detailText: "")
    let helpMailAddressApply = ApplyPersonInfo(titleName: "邮寄通讯地址", type: .enter, placeholder: "请输入邮寄通讯地址", detailText: "")
    let helpMailCodeApply = ApplyPersonInfo(titleName: "签收邮编", type: .enter, placeholder: "请输入签收邮编", detailText: "")
    let getMethod = ApplyPersonInfo(titleName: "结论书领取方式", type: .choose, placeholder: "", detailText: "", chooseType: "38")
    
    func fetchDataIfNeed(finished: @escaping ()->(Void)) {
        
        if !marriedApply.chooseArray.isEmpty &&
            !helpRelationApply.chooseArray.isEmpty &&
            !getMethod.chooseArray.isEmpty {
            finished()
            return
        }
        let taskCount = Variable(0)
        CDUtility.showHud()
        _ = taskCount.asObservable().skip(1).subscribe(onNext: { (value) in
            if value == 0 {
                CDUtility.hidHud()
                finished()
            }
        }, onError: nil, onCompleted: nil, onDisposed: nil)
        if marriedApply.chooseArray.isEmpty {
            taskCount.value = 1
            marriedApply.getData(marriedApply.chooseType, finished: {
                taskCount.value = taskCount.value - 1
            })
            return
        }
        if helpRelationApply.chooseArray.isEmpty {
            taskCount.value = taskCount.value + 1
            helpRelationApply.getData(helpRelationApply.chooseType, finished: {
                taskCount.value = taskCount.value - 1
            })
            return
        }
        if getMethod.chooseArray.isEmpty {
            taskCount.value = taskCount.value + 1
            getMethod.getData(getMethod.chooseType, finished: {
                taskCount.value = taskCount.value - 1
            })
            return
        }
        
    }
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "填写个人资料"
        configData()
        
        guard let _ = MyselfSingleton.shared.userInfo else {
            navigationController?.popViewController(animated: true)
            return
        }
        
        tableView.register(UINib(nibName: "ApplyPersonStaticInfoCell", bundle: nil), forCellReuseIdentifier: "ApplyPersonStaticInfoCell")
        tableView.register(UINib(nibName: "ApplyPersonInfoCell", bundle: nil), forCellReuseIdentifier: "ApplyPersonInfoCell")
        
        tableView.snp.remakeConstraints { (maker) in
            maker.left.right.equalTo(view)
            if #available(iOS 11.0, *){
                // ios11以上
                maker.top.equalTo(view.safeAreaLayoutGuide)
                maker.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-60)
            }
            else
            {
                maker.top.equalTo(topLayoutGuide.snp.bottom)
                maker.bottom.equalTo(bottomLayoutGuide.snp.top).offset(-60)
            }
        }
        
        dataSourceFirst = [
            // base
            nameApply,
            sexApply,
            birthApply,
            idApply,
            shebaoIDApply,
            // other
            marriedApply,
            homeTownApply,
            liveAddress,
            teleApply,
            mobileApply
        ]
        
        dataSourceSecond = [
            helpNameApply,
            helpTeleApply,
            helpMobile,
            helpRelationApply,
            helpSMSApply,
            getMethod,
            helpMailReceiverApply,
            helpMailAddressApply,
            helpMailCodeApply,
        ]
        
        _ = getMethod.detailText.asObservable().subscribe(onNext: { [weak self] (str) in
            if let strongSelf = self {
                strongSelf.tableView.reloadData()
                strongSelf.tableView.scrollToRow(at: IndexPath(row: strongSelf.dataSourceSecond.count - 1, section: 1), at: UITableViewScrollPosition.top, animated: true)

            }
        }, onError: nil, onCompleted: nil, onDisposed: nil)

        tableView.reloadData()
    }
    
    func configData() {
        guard let info = MyselfSingleton.shared.userInfo else {
            return
        }
        nameApply.detailText.value = info.name
        sexApply.detailText.value = info.sex
        birthApply.detailText.value = info.birthday()
        idApply.detailText.value = info.userID
        shebaoIDApply.detailText.value = info.personNum
        
        nameApply.save("nameApply")
        sexApply.save("sexApply")
        birthApply.save("birthApply")
        idApply.save("idApply")
        shebaoIDApply.save("shebaoIDApply")
        
        // other
        marriedApply.config("marriedApply")
        homeTownApply.config("homeTownApply")
        liveAddress.config("liveAddress")
        teleApply.config("teleApply")
        mobileApply.config("mobileApply")
        
        helpTeleApply.config("helpTeleApply")
        helpMobile.config("helpMobile")
        helpRelationApply.config("helpRelationApply")
        helpSMSApply.config("helpSMSApply")
        helpMailReceiverApply.config("helpMailReceiverApply")
        helpMailAddressApply.config("helpMailAddressApply")
        helpMailCodeApply.config("helpMailCodeApply")
        helpNameApply.config("helpNameApply")
        getMethod.config("getMethod")
    }
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return section == 0 ? dataSourceFirst.count : dataSourceSecond.count
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = UIView(frame: CGRect(x: 0, y: 0, width: DeviceInfo.screenWidth, height: 30))
        view.backgroundColor = UIColor.lightGray
        
        let label = UILabel()
        label.text = section == 0 ? "个人资料" : "监护人资料"
        label.textColor = UIColor.darkGray
        label.font = UIFont.systemFont(ofSize: 13.0)
        view.addSubview(label)
        
        label.snp.remakeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalTo(10)
        }
        
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 30.0
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var model = dataSourceFirst[indexPath.row]
        
        if indexPath.section == 1 {
            model = dataSourceSecond[indexPath.row]
        }
        
        switch model.type {
        case .base:
            let cell = tableView.dequeueReusableCell(withIdentifier: "ApplyPersonStaticInfoCell", for: indexPath) as! ApplyPersonStaticInfoCell
            cell.model = model
            return cell
        default:
            let cell = tableView.dequeueReusableCell(withIdentifier: "ApplyPersonInfoCell", for: indexPath) as! ApplyPersonInfoCell
            cell.model = model
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 1 && indexPath.row > 5 {
            return getMethod.chooseModel.name == "邮寄" ? 44.0 : 0.01
        }
        return 44.0
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        view.endEditing(true)
    }
    
    
    func enterFull() -> Bool {
        if marriedApply.detailText.value.count == 0 {
            if view.window != nil {
                makeToast("请选择/填写-\(marriedApply.titleName)")
            }
            return false
        }
        if homeTownApply.detailText.value.count == 0 {
            if view.window != nil {
                makeToast("请选择/填写-\(homeTownApply.titleName)")
            }
            return false
        }
        if liveAddress.detailText.value.count == 0 {
            if view.window != nil {
                makeToast("请选择/填写-\(liveAddress.titleName)")
            }
            return false
        }
//        if teleApply.detailText.value.count == 0 {
//            if view.window != nil {
//                makeToast("请选择/填写-\(teleApply.titleName)")
//            }
//            return false
//        }
        if mobileApply.detailText.value.count == 0 {
            if view.window != nil {
                makeToast("请选择/填写-\(mobileApply.titleName)")
            }
            return false
        }

        // section 1
        if helpNameApply.detailText.value.count == 0 {
            if view.window != nil {
                makeToast("请选择/填写-\(helpNameApply.titleName)")
            }
            return false
        }
//        if helpTeleApply.detailText.value.count == 0 {
//            if view.window != nil {
//                makeToast("请选择/填写-\(helpTeleApply.titleName)")
//            }
//            return false
//        }
        if helpMobile.detailText.value.count == 0 {
            if view.window != nil {
                makeToast("请选择/填写-\(helpMobile.titleName)")
            }
            return false
        }
        if helpRelationApply.detailText.value.count == 0 {
            if view.window != nil {
                makeToast("请选择/填写-\(helpRelationApply.titleName)")
            }
            return false
        }
        if helpSMSApply.detailText.value.count == 0 {
            if view.window != nil {
                makeToast("请选择/填写-\(helpSMSApply.titleName)")
            }
            return false
        }
        
        if getMethod.detailText.value.count == 0 {
            if view.window != nil {
                makeToast("请选择/填写-\(getMethod.titleName)")
            }
            return false
        }
        if getMethod.detailText.value == "邮寄" {
            
            if helpMailReceiverApply.detailText.value.count == 0 {
                if view.window != nil {
                    makeToast("请选择/填写-\(helpMailReceiverApply.titleName)")
                }
                return false
            }
            
            if helpMailAddressApply.detailText.value.count == 0 {
                if view.window != nil {
                    makeToast("请选择/填写-\(helpMailAddressApply.titleName)")
                }
                return false
            }
            
            if helpMailCodeApply.detailText.value.count == 0 {
                if view.window != nil {
                    makeToast("请选择/填写-\(helpMailCodeApply.titleName)")
                }
                return false
            }
        }
        return true
    }
    
    func requestData() -> [String: Any] {
        var requestData = [String: Any]()
        requestData["BRXM"] = nameApply.detailText.value
        requestData["BRXB"] = sexApply.detailText.value == "男" ? "1" : "2"
        requestData["CSNY"] = birthApply.detailText.value
        requestData["GDDH"] = teleApply.detailText.value
        requestData["HJDZ"] = homeTownApply.detailText.value
        requestData["HYZK"] = marriedApply.chooseModel.id
        requestData["JHGX"] = helpRelationApply.chooseModel.id
        requestData["JHRGDDH"] = helpTeleApply.detailText.value
        requestData["JHRDZ"] = helpMailAddressApply.detailText.value
        requestData["JHRM"] = helpNameApply.detailText.value
        requestData["JHRYB"] = ""
        requestData["JHRYDDH"] = helpMobile.detailText.value
        requestData["JLSLQFS"] = getMethod.chooseModel.id
        requestData["JZDZ"] = liveAddress.detailText.value
        requestData["PGGWJT"] = 0
        requestData["PGHM"] = 0
        requestData["PGSSZJZ"] = 0
        requestData["QSDZ"] = helpMailAddressApply.detailText.value
        requestData["QSRM"] = helpMailReceiverApply.detailText.value
        requestData["QSRSJHM"] = helpSMSApply.detailText.value
        requestData["QSYB"] = helpMailCodeApply.detailText.value
        requestData["SBHM"] = shebaoIDApply.detailText.value
        requestData["SFZH"] = idApply.detailText.value
        requestData["YDDH"] = mobileApply.detailText.value
        requestData["YYSJLB"] = 0
        requestData["YZBM"] = ""
        
        //        [{
        //            "BRXB":性别1男2女 ,
        //            "BRXM":"姓名",
        //            "CSNY":"1969.01.15出生年月",
        //            "GDDH":"住宅电话",
        //            "HJDZ":"户籍地址",
        //            "HYZK":婚姻状况字典序号,
        //            "JHGX":监护关系字典序号,
        //            "JHRDZ":"",
        //            "JHRGDDH":"监护人固定电话",
        //            "JHRM":"监护人",
        //            "JHRYB":"",
        //            "JHRYDDH":"监护人手机",
        //            "JLSLQFS":结论书领取方式字典序号,
        //            "JZDZ":"居住地",
        //            "PGGWJT":0,
        //            "PGHM":0,
        //            "PGSSZJZ":0,
        //            "QSDZ":"签收地址",
        //            "QSRM":"签收人名",
        //            "QSRSJHM":"短信通知手机号码",
        //            "QSYB":"签收邮编",
        //            "SBHM":"个人编号",
        //            "SFZH":"身份证号",
        //            "YDDH":"移动电话",
        //            "YYSJLB":0,
        //            "YZBM":""}]
        return requestData
    }
    
    func cleanData() {
        marriedApply.clean("marriedApply")
        homeTownApply.clean("homeTownApply")
        liveAddress.clean("liveAddress")
        teleApply.clean("teleApply")
        mobileApply.clean("mobileApply")
        
        helpTeleApply.clean("helpTeleApply")
        helpMobile.clean("helpMobile")
        helpRelationApply.clean("helpRelationApply")
        helpSMSApply.clean("helpSMSApply")
        helpMailReceiverApply.clean("helpMailReceiverApply")
        helpMailAddressApply.clean("helpMailAddressApply")
        helpMailCodeApply.clean("helpMailCodeApply")
        helpNameApply.clean("helpNameApply")
        getMethod.clean("getMethod")
    }
    
    @IBAction func submitAction(_ sender: Any) {
        
        if mobileApply.detailText.value.count != 11 || IntValue(value: mobileApply.detailText.value) == 0 {
            makeToast("请检查-移动电话")
            return
        }
        
        if helpMobile.detailText.value.count != 11 || IntValue(value: helpMobile.detailText.value) == 0 {
            makeToast("请检查-监护人移动电话")
            return
        }
        
        if helpSMSApply.detailText.value.count != 11 || IntValue(value: helpSMSApply.detailText.value) == 0 {
            makeToast("请检查-短信通知手机号")
            return
        }
        
        if !enterFull() {
            return
        }

        // other
        marriedApply.save("marriedApply")
        homeTownApply.save("homeTownApply")
        liveAddress.save("liveAddress")
        teleApply.save("teleApply")
        mobileApply.save("mobileApply")
        
        helpTeleApply.save("helpTeleApply")
        helpMobile.save("helpMobile")
        helpRelationApply.save("helpRelationApply")
        helpSMSApply.save("helpSMSApply")
        helpMailReceiverApply.save("helpMailReceiverApply")
        helpMailAddressApply.save("helpMailAddressApply")
        helpMailCodeApply.save("helpMailCodeApply")
        helpNameApply.save("helpNameApply")
        getMethod.save("getMethod")
        
        makeToast("保存成功")
        navigationController?.popViewController(animated: true)
    }
}
